package repository

import (
	"oa-system/internal/model"
	"oa-system/pkg/errors"

	"gorm.io/gorm"
)

type DepartmentRepository interface {
	GetAllDepartments(page, pageSize int, name string) ([]model.Department, int64, error)
	GetDepartmentByID(id uint) (*model.Department, error)
	CreateDepartment(department *model.Department) (*model.Department, error)
	UpdateDepartment(department *model.Department) (*model.Department, error)
	DeleteDepartment(id uint) error
}

type departmentRepository struct {
	db *gorm.DB
}

func NewDepartmentRepository(db *gorm.DB) DepartmentRepository {
	return &departmentRepository{db: db}
}

func (r *departmentRepository) GetAllDepartments(page, pageSize int, name string) ([]model.Department, int64, error) {
	var departments []model.Department
	var total int64

	query := r.db.Model(&model.Department{})

	if name != "" {
		query = query.Where("name LIKE ?", "%"+name+"%")
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, errors.NewInternalServerError("获取部门总数失败", err)
	}

	offset := (page - 1) * pageSize
	if err := query.Offset(offset).Limit(pageSize).Find(&departments).Error; err != nil {
		return nil, 0, errors.NewInternalServerError("获取部门列表失败", err)
	}

	return departments, total, nil
}

func (r *departmentRepository) GetDepartmentByID(id uint) (*model.Department, error) {
	var department model.Department
	if err := r.db.First(&department, id).Error; err != nil {
		return nil, errors.NewNotFoundError("部门不存在", err)
	}
	return &department, nil
}

func (r *departmentRepository) CreateDepartment(department *model.Department) (*model.Department, error) {
	if err := r.db.Create(department).Error; err != nil {
		return nil, errors.NewInternalServerError("创建部门失败", err)
	}
	return department, nil
}

func (r *departmentRepository) UpdateDepartment(department *model.Department) (*model.Department, error) {
	err := r.db.Omit("created_at").Updates(department).Error
	if err != nil {
		return nil, errors.NewInternalServerError("更新部门失败", err)
	}
	return department, nil
}

func (r *departmentRepository) DeleteDepartment(id uint) error {
	// 检查是否有子部门
	var count int64
	if err := r.db.Model(&model.Department{}).Where("parent_id = ?", id).Count(&count).Error; err != nil {
		return errors.NewInternalServerError("检查子部门失败", err)
	}
	if count > 0 {
		return errors.NewBadRequestError("该部门下还有子部门，无法删除", nil)
	}

	// 检查是否有用户
	if err := r.db.Model(&model.User{}).Where("department_id = ?", id).Count(&count).Error; err != nil {
		return errors.NewInternalServerError("检查部门下用户失败", err)
	}
	if count > 0 {
		return errors.NewBadRequestError("该部门下还有用户，无法删除", nil)
	}

	if err := r.db.Delete(&model.Department{}, id).Error; err != nil {
		return errors.NewInternalServerError("删除部门失败", err)
	}
	return nil
}
